package com.wulian.user.controller;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wulian.common.controller.BaseController;
import com.wulian.common.util.JSONUtil;
import com.wulian.common.vo.ResultMoudel;
import com.wulian.user.dto.PostUserDto;
import com.wulian.user.entity.Post;
import com.wulian.user.entity.PostUser;
import com.wulian.user.mapper.PostMapper;
import com.wulian.user.mapper.PostUserMapper;
import com.wulian.user.service.PostUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 *@Description:()
 * @author  caifulin
 * @date  2020/10/27 9:31
 * @version 1.0
 */
@RestController
@RequestMapping("/post")
@Api(value = "岗位",tags = {"岗位管理接口"})
@Slf4j
public class PostController extends BaseController<Post> {


    @Autowired
    private PostMapper postMapper;

    @Autowired
    private PostUserMapper postUserMapper;

    @Autowired
    private PostUserService postUserService;
    /**
     * 新增或编辑
     */
    @PostMapping("/save")
    @ApiOperation(value = "岗位新增或编辑",httpMethod = "POST",notes = "有Id修改没id新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "岗位名称", required = false, dataType = "String"),

            @ApiImplicitParam(name = "describe", value = "岗位描述", required = false, dataType = "String")
    })
    public ResultMoudel save(@RequestBody Post post){
        Date newDate = new Date();
        Integer userId = getCurrentUser().getSysUser().getUserId();
        Integer companyId = getCurrentUser().getSysUser().getCompanyId();
        post.setUpdateTime(newDate);
        post.setDelFlag(0);
        Integer flag = 0;
        if(post.getId() != null){
            post.setUpdateId(userId);
            flag = postMapper.updateById(post);
        }else{
            post.setCreateId(userId);
            post.setCompanyId(companyId);
            post.setCreateTime(newDate);
            post.setUpdateTime(newDate);
            post.setUpdateId(userId);
            flag = postMapper.insert(post);
        }
        if(0 == flag.intValue()){
            return new ResultMoudel().error("操作失败");
        }
        return new ResultMoudel().success("操作成功");
    }

   /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "Integer")
     })
    @ApiOperation(value = "删除",httpMethod = "POST",notes = "")
    public ResultMoudel delete(@RequestBody Post post){
        ResultMoudel resultMoudel = new ResultMoudel();
        if(null == post || null == post.getId()){
            return resultMoudel.error("参数异常");
        }

        Integer companyId = getCurrentUser().getSysUser().getCompanyId();
        post.setCompanyId(companyId);
        post.setDelFlag(0);
        Post result = postMapper.selectOne(post);
        Date newDate = new Date();
        if(result != null){
            Post updatePost = new Post();
            updatePost.setUpdateId(getCurrentUser().getSysUser().getUserId());
            updatePost.setUpdateTime(newDate);
            updatePost.setDelFlag(1);
            //Integer integer = postMapper.updateById(updatePost);
            Post where = new Post();
            where.setCompanyId(companyId);
            where.setId(result.getId());
            EntityWrapper<Post> postEntityWrapper = new EntityWrapper<>(where);
            Integer update = postMapper.update(updatePost, postEntityWrapper);
            if(0 == update.intValue()){
                return resultMoudel.error("操作失败");
            }
            return resultMoudel.success("操作成功");
        }else{
            return resultMoudel.error("没有找到该对象");
        }
    }

    /**
     * 查询
     */
    @PostMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "Integer")
    })
    @ApiOperation(value = "查询",httpMethod = "POST",notes = "")
    public ResultMoudel find(@RequestBody Post post){
        ResultMoudel resultMoudel = new ResultMoudel();
        Integer companyId = getCurrentUser().getSysUser().getCompanyId();
        post.setCompanyId(companyId);
        post.setDelFlag(0);
        Post result = postMapper.selectOne(post);
        if(null != result){
            return resultMoudel.success(result);
        }else{
            return resultMoudel.error("没有找到该对象");
        }
    }

    /**
     * 分页查询
     */
    @PostMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "岗位名称", required = false, dataType = "string")
    })
    public ResultMoudel list(@RequestBody Post post,
                       @RequestParam(required = false, defaultValue = "0") int num,
                       @RequestParam(required = false, defaultValue = "10") int pageSize) {
        //分页构造器
        Page<Post> page = new Page<Post>(num,pageSize);
        //条件构造器
        EntityWrapper<Post> queryWrapperw = new EntityWrapper<Post>();
        queryWrapperw.eq("del_flag","0");
        queryWrapperw.and().eq("company_id",getCurrentUser().getSysUser().getCompanyId());
        if(StringUtils.isNotEmpty(post.getName())){
            queryWrapperw.and().like("name",post.getName());
        }
        if(StringUtils.isNotEmpty(post.getDescribe())){
            queryWrapperw.and().like("describe",post.getDescribe());
        }
        if(null != post.getType()){
            queryWrapperw.and().eq("type",post.getType());
        }
        //执行分页
        List<Post> posts = postMapper.selectPage(page, queryWrapperw);
        page.setRecords(posts);
        //返回结果
        return new ResultMoudel().success(page);
    }


    /**
     * 查询岗位人员信息
     */
    @PostMapping("/queryPostUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "岗位Id", required = true, dataType = "int")
    })
    public ResultMoudel queryPostUser(@RequestBody Post post) {
        if(post.getId() == null){
            return new ResultMoudel().error("参数异常");
        }
        Integer companyId = getCurrentUser().getSysUser().getCompanyId();
        PostUser postUser = new PostUser();
        postUser.setDelFlag(0);
        postUser.setCompanyId(companyId);
        postUser.setPostId(post.getId());
        EntityWrapper<PostUser> postUserEntityWrapper = new EntityWrapper(postUser);
        List<PostUser> postUsers = postUserMapper.selectList(postUserEntityWrapper);
        return new ResultMoudel().success(postUsers);
    }

    /**
     * 更新岗位人员信息
     */
    @PostMapping("/updatePostUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "更新岗位人员信息", required = false, dataType = "string")
    })
    public ResultMoudel updatePostUser(@RequestBody PostUserDto postUserDto) {
        if(null == postUserDto || null == postUserDto.getPostId() || null == postUserDto.getUserIdList()){
            return new ResultMoudel().error("参数异常");
        }
        Integer companyId = getCurrentUser().getSysUser().getCompanyId();
        Integer userId = getCurrentUser().getSysUser().getUserId();
        postUserDto.setCompanyId(companyId);
        ResultMoudel resultMoudel = postUserService.updatePostUser(postUserDto,userId);
        return resultMoudel;
    }
    /**
     * 列表查询
     */
    @PostMapping("/find")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "岗位名称", required = false, dataType = "string")
    })
    public ResultMoudel list(@RequestBody Post post) {

        //条件构造器
        EntityWrapper<Post> queryWrapperw = new EntityWrapper<Post>();
        queryWrapperw.and().eq("company_id",getCurrentUser().getSysUser().getCompanyId());
        if(StringUtils.isNotEmpty(post.getName())){
            queryWrapperw.and().like("name",post.getName());
        }
        if(null != post.getType()){
            queryWrapperw.and().eq("type",post.getType());
        }
        queryWrapperw.eq("del_flag","0");
        List<Post> posts = postMapper.selectList(queryWrapperw);
        //返回结果
        return new ResultMoudel().success(posts);
    }
    
    @PostMapping("/getUserIdListByPlaceWorkId")
    @ResponseBody
    public List<String> getUserIdListByPlaceWorkId(@RequestBody String placeWorkId){
    	
        log.info("查询岗位参数placeWorkId：{}",placeWorkId);
    	if(org.apache.commons.lang3.StringUtils.isBlank(placeWorkId)){
    		return null;
    	}
    	
    	HashMap<String,Object> hashMap = new HashMap<String,Object>();
    	
    	List<String> list = Arrays.asList(placeWorkId.split(","));
    	List<String> userIdList = new ArrayList<String>();
    	list.forEach(s ->{
    		hashMap.put("post_id", s);
    		List<PostUser> selectByMap = postUserMapper.selectByMap(hashMap);
    		if(null != selectByMap && selectByMap.size() > 0){
    			userIdList.addAll(selectByMap.stream().map(pu -> String.valueOf(pu.getUserId())).collect(Collectors.toList()));
    		}
    		
    	});
    	log.info("查询岗位返回结果userIdList：{}",JSONUtil.toJSON(userIdList));
    	return userIdList;
    }

}